﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace famails.App_Code
{
    public class DbHelper
    {
        string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        public DbHelper()
        {

        }
        public DataTable GetTable(string sql, params object[] parameters)
        {
            SqlCommand cmd = CreateCommand(sql, parameters);
            DataTable T = new DataTable();
            SqlDataAdapter data = new SqlDataAdapter(cmd);
            data.Fill(T);
            cmd.Connection.Close();
            return T;
        }
        public int ExecuteNoneQuery(string sql, params object[] parameters)
        {
            int result = 0;
            SqlCommand cmd = CreateCommand(sql, parameters);
            result = cmd.ExecuteNonQuery();
            cmd.Connection.Close();
            return result;
        }
        public object ExecuteScalar(string sql, params object[] parameters)
        {
            object result = 0;
            SqlCommand cmd = CreateCommand(sql, parameters);
            result = cmd.ExecuteScalar();
            cmd.Connection.Close();
            return result;
        }
        public SqlCommand CreateCommand(string sql, params object[] parameters)
        {
            SqlConnection conn = new SqlConnection(ConnectionString);
            SqlCommand cmd = new SqlCommand(sql, conn);
            if (sql.Trim().IndexOf(' ') < 0)
                cmd.CommandType = CommandType.StoredProcedure;
            if (cmd.Connection.State != ConnectionState.Open)
                conn.Open();
            if (parameters.Length > 0)
            {
                SqlParameter para;
                for (int i = 0; i < parameters.Length; i++)
                {
                    para = new SqlParameter(parameters[i] + "", parameters[i + 1]);
                    cmd.Parameters.Add(para);
                    i += 1;
                }
            }
            return cmd;
        }
    }
}